package com.example.demoserver.util;


import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Configuration
public class JwtInterceptor implements HandlerInterceptor {
    private final AppPropertyConfig appPropertyConfig;

    public JwtInterceptor(AppPropertyConfig appPropertyConfig) {
        this.appPropertyConfig = appPropertyConfig;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从http请求头获取token
        Cookie[] cookies = request.getCookies();
        try {
            //如果验证成功放行请求
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if ((appPropertyConfig.getName()+"-token").equals(cookie.getName())) {
                        String token = cookie.getValue();
                        DecodedJWT verify = JWTUtil.verify(token);
                        String role = verify.getClaim("role").asString();
                        return true;
                    }

                }

            }
        }
        catch (Exception exception)
        {
            System.out.println(exception.getMessage());
        }
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    }


}
